package com.eboss2.sbs.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ScrollView;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.ActivityGetEms;
import com.eboss2.sbs.activity.ActivityOrderDetail;
import com.eboss2.sbs.adapter.OrderManagerAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.interfaces.OrderManagerCallBackListener;
import com.eboss2.sbs.model.MessageEvent;
import com.eboss2.sbs.model.OrderManagerInfo;
import com.eboss2.sbs.myapplication.MyApplication;
import com.eboss2.sbs.weight.MyCustomDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.views.MyDialog;
import com.tool.utils.utils.LogUtils;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.view.MyListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class FragmentOrderManagerTkjj extends AbstractFragment{
    private static final String TAG = "FragmentOrderManagerTkjj";

    private PullToRefreshScrollView mPullRefreshScrollView;
    private List<OrderManagerInfo> orderManagerInfos = new ArrayList<>();
    private OrderManagerAdapter adapter;
    private MyListView myListView;
    private int page = 1;
    private boolean showProgress = false;
    private static Context sContext;

    public static final byte ORDER_STATUS_CREATE = 6;//新订单
    public static final byte ORDER_STATUS_COMFIG = 8; //待发送
    public static final byte ORDER_STATUS_SEND = 7; //已发货
    public static final byte ORDER_STATUS_FINISH = 9; //确认收货


    @Override
    protected void initView() {

        showProgress = false;
        sContext = mContext;

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

//        for (int i = 0; i < 7; i++){
//            OrderManagerInfo orderManagerInfo = new OrderManagerInfo();
//            orderManagerInfo.setOrderStatus(1+i);
//            orderManagerInfo.setOrderNo("111111");
//            orderManagerInfo.setAddress("浙江省,嘉兴市,平湖市当湖街道人民东路150弄23号楼1202室");
//            orderManagerInfo.setEmsAmt(1111);
//            orderManagerInfo.setName("XXXXX");
//            orderManagerInfo.setNum(11);
//            orderManagerInfo.setOrderAmt(111);
//            orderManagerInfo.setPhone("14782108167");
//            orderManagerInfo.setUserName("1212");
//            orderManagerInfo.setRecipient("张三");
//            orderManagerInfo.setEmsName("中通快递");
//            orderManagerInfo.setEmsNo("111111111111111");
//            orderManagerInfo.setEmsContent("浙江省温州市永嘉县上塘镇公司(点击查询电话)叶** 派件中 派件员电话17805872026");
//            orderManagerInfo.setEmsTime("2018-02-23 16:12:11");
//
//            List<OrderListInfo> orderListInfos = new ArrayList<>();
//            for(int j = 0; j < 2; j++) {
//                OrderListInfo orderListInfo = new OrderListInfo();
//                orderListInfo.setCount(4);
//                orderListInfo.setImgUrl("");
//                orderListInfo.setName("新货原味无漂白开心果新货坚果..新货原味无漂白开心果新货坚果.");
//                orderListInfo.setNewAmt(111);
//                orderListInfo.setOldAmt(222);
//                orderListInfos.add(orderListInfo);
//            }
//            orderManagerInfo.setOrderListInfo(orderListInfos);
//            orderManagerInfos.add(orderManagerInfo);
//        }


        myListView = findViewById(R.id.listview);
        adapter = new OrderManagerAdapter(mContext, orderManagerInfos, new OrderManagerCallBackListener() {
            @Override
            public void addBack(long id, String data, ImageView img_qi, MyCustomDialog dialog) {
//                setAddBack(id, data, img_qi, dialog);
            }

            @Override
            public void setFh(long id, String emsName, String emsShortName, String expressNo, MyCustomDialog dialog) {
//                startActivity(new Intent(mContext, ActivityGetEms.class).putExtra("id", id).putExtra("type", "ywc"));
            }

            @Override
            public void setZt(long id) {

            }

            @Override
            public void setCancalOrder(final long id) {
                MyDialog.Builder builder = new MyDialog.Builder(mContext);
                builder.setTitle("提示");
                builder.setMessage("确定取消订单吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        doCancalOrder(id, dialog);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }

            @Override
            public void EditPrice(long id, Integer goodAmount, Integer freightCharge) {

            }

            @Override
            public void RefundSure(long id, DialogInterface dialog, String amt, String content) {

            }

            @Override
            public void RefundRefused(long id, MyCustomDialog dialog, String reason) {

            }


        });
        myListView.setAdapter(adapter);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                ToastUtils.CustomShow(mContext, ""+i);
                startActivity(new Intent(mContext, ActivityOrderDetail.class).putExtra("status", orderManagerInfos.get(i).getStatus()).putExtra("orderId", orderManagerInfos.get(i).getId()));

            }
        });


        mPullRefreshScrollView = findViewById(R.id.pull_refresh_scrollview);
        // 下拉刷新、上拉加载更多
        mPullRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        // TODO:必须先设置Mode后再设置刷新文本
        ILoadingLayout startLabels = mPullRefreshScrollView.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在载入...");// 刷新时
        startLabels.setReleaseLabel("释放立即刷新...");// 下来达到一定距离时，显示的提示
        // TODO:必须先设置Mode后再设置刷新文本
        ILoadingLayout endLabels = mPullRefreshScrollView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉加载更多...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("正在载入...");// 刷新时
        endLabels.setReleaseLabel("释放立即加载...");// 下来达到一定距离时，显示的提示
        mPullRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                // 下拉刷新
                String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy(true, false).setLastUpdatedLabel("更新于：" + label);
                reloadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                // 上拉加载更多
                String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy(false, true).setLastUpdatedLabel("更新于：" + label);


                if (orderManagerInfos.size() == 0) {
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            showErrorMsg("没有更多了");
                            mPullRefreshScrollView.onRefreshComplete();
                        }
                    }, 1000);
                }else{
                    page++;
                    loadData();
                }


            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        if ("ywc".equals(messageEvent.getMessage())) {
            reloadData();
        }
    }





    private void doCancalOrder(long id, final DialogInterface dialog) {


        showProgress("加载中...");
        String url = Config.SBS_CLOSE_ORDER;
        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("status", 10);

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    dialog.dismiss();
                    reloadData();

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });

    }



    private void setAddBack(long id, String data, final ImageView img_qi, final MyCustomDialog dialog){
        showProgress("加载中...");

        String url = Config.SBS_ADD_REMAKE;
        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("remark", data);

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    //保存备注，成功更改旗子
//                    img_qi.setImageResource(R.mipmap.icon_qi2);
//                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    reloadData();

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });
    }

    protected void lazyLoad() {
        LogUtils.e(TAG1+TAG, "lazyLoad()");
        reloadData();
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_order_manager_all;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e(TAG1+TAG, "onResume");
//        reloadData();
    }


    /**
     * 重新加载数据
     */
    private void reloadData() {
        page = 1;
        orderManagerInfos.clear();
        loadData();
    }


    private void loadData() {


        if (showProgress){
            return;
        }

        showProgress = true;

        String url = Config.SBS_MALL_ORDER_LIST;
        RequestParams params = new RequestParams();
        params.put("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid()+"");
        params.put("status", "10");
        params.put("pageNo",page+"");
        params.put("pageSize","15");
        showProgress("加载中...");

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @Override
            public void success(String response) {
                showProgress = false;
                disShowProgress();
                try {

                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        // 刷新完成
                        mPullRefreshScrollView.onRefreshComplete();
                        return;
                    }
                    JSONObject obj = result.getJSONObject("data");
                    String orderList = obj.optString("orderList");
                    if (!StringUtils.isBlank(orderList)) {

                        Gson gson = new Gson();
                        // json数据转换成List
                        List<OrderManagerInfo> datas = gson.fromJson(orderList, new TypeToken<List<OrderManagerInfo>>() {
                        }.getType());


                        if (datas.size() > 0) {
                            orderManagerInfos.addAll(datas);
                            if (orderManagerInfos.size() > 0) {
                                linearLayout(R.id.id_no_data).setVisibility(View.GONE);
                                myListView.setVisibility(View.VISIBLE);
                            } else {
                                linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
                                myListView.setVisibility(View.GONE);
                            }

                        } else {
                            if (orderManagerInfos.size() > 0) {

                                linearLayout(R.id.id_no_data).setVisibility(View.GONE);
                                myListView.setVisibility(View.VISIBLE);
                                handler.postDelayed(new Runnable() {

                                    @Override
                                    public void run() {
                                        showErrorMsg("没有更多数据");
                                    }
                                }, 1000);
                            } else {
                                linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
                                myListView.setVisibility(View.GONE);
                            }
                        }
                    }
                    // 刷新完成
                    mPullRefreshScrollView.onRefreshComplete();
                    adapter.notifyDataSetChanged();



                } catch (JSONException e) {
                    e.printStackTrace();
                    mPullRefreshScrollView.onRefreshComplete();
                }
            }

            @Override
            public void failed(Throwable error) {
                showProgress = false;
                mPullRefreshScrollView.onRefreshComplete();
                showE404();
                disShowProgress();
            }
        });
    }






}
